<?php

namespace app\api\controller;

use app\admin\model\Order as AdminModelOrder;
use app\admin\model\ServersUser;
use app\admin\model\SystemConfig;
use app\api\model\Goods;
use app\api\model\GoodsProduct;
use app\api\model\Order as ModelOrder;
use app\api\model\OrderItem;
use app\api\model\ServerUser;
use app\api\model\ServiceTime;
use app\api\model\SuserItem;
use app\api\model\User;
use app\api\model\UserAddress;
use app\common\controller\ApiController;
use think\App;
use think\facade\Db;
use think\facade\Env;
use WeChat\Pay;
use \app\admin\traits\Curd;
use app\api\model\AfterOrder;
use app\api\model\AfterOrderItem;
use app\api\model\AttachOrder;
use app\api\model\Finance;
use app\api\model\OrderRecord;
use app\Request;

class Order extends ApiController
{

    protected $noNeedLogin = [];
    protected $mustLogin = [];

    protected $wechat_config = [];
    // protected $allowModifyFileds = ['username', 'sort', 'status_text'];

    use \app\admin\traits\Curd;

    public function __construct(App $app)
    {
        $this->wechat_config = [
            // 'token'          => 'test',
            'appid' => Env::get('pay.appid'),
            'appsecret' => '',
            'encodingaeskey' => '',
            // 配置商户支付参数（可选，在使用支付功能时需要）
            'mch_id' => Env::get('pay.mchid'),
            'mch_key' => Env::get('pay.apikey'),
            // 配置商户支付双向证书目录（可选，在使用退款|打款|红包时需要）
            'ssl_key' => root_path() . '/cert/apiclient_key.pem',
            'ssl_cer' => root_path() . '/cert/apiclient_cert.pem',
            // 缓存目录配置（可选，需拥有读写权限）
            'cache_path' => '',
        ];
        parent::__construct($app);
        $this->model = new ModelOrder();
    }

    /**
     * 下单预约
     */
    public function create_order()
    {
        $param = $this->request->param();
        if (empty($param['address_id'])) {
            $this->error('请选择地址');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('达人id不能为空');
        }
        if (empty($param['service_goodid'])) {
            $this->error('项目id不能为空');
        }
        // if (empty($param['distance'])) {
        //     $this->error('上门路程不能为空');
        // }
        if (empty($param['service_duration'])) {
            $this->error('服务时长不能为空');
        }
        if (empty($param['appointment_date'])) {
            $this->error('预约日期不能为空');
        }
        if (empty($param['appointment_time'])) {
            $this->error('预约时间不能为空');
        }
        if (empty($param['time_period'])) {
            $this->error('预约时间段不能为空');
        }
        // $daytime_starting_price = sysconfig('daytime','daytime_starting_price');//白天起步价
        // $daytime_additional_costs = sysconfig('daytime','daytime_additional_costs');//白天每增加1公里的额外费用
        // $daytime_additional_fees = sysconfig('daytime','daytime_additional_fees');//白天附加费用

        // $night_starting_price = sysconfig('night','night_starting_price');//晚上起步价
        // $night_additional_costs = sysconfig('night','night_additional_costs');//晚上每增加1公里的额外费用
        // $night_additional_fees = sysconfig('night','night_additional_fees');//晚上附加费用

        // //根据时间段判断是否是晚上  1上午  2下午  3晚上   
        // if($param['time_period'] == 3){
        //     //计算出租车费用  车费补助
        //     $calculate_taxi_fare = $this->calculate_taxi_fare($param['distance'],$night_starting_price,$night_additional_costs,$night_additional_fees);
        // }else{
        //     //计算出租车费用  车费补助
        //     $calculate_taxi_fare = $this->calculate_taxi_fare($param['distance'],$daytime_starting_price,$daytime_additional_costs,$daytime_additional_fees);
        // }
        
        $service_goods = Db::name("service_goods")->where("id",$param["service_goodid"])->find();
        
        $service_price = bcmul($service_goods["price"],$param['service_duration'],2);
         

       // $total_price = bcadd($calculate_taxi_fare,$service_price,2);
        $total_price = $service_price;
      
        
        $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $this->uid;
        $data = [ 
            'address_id'=>$param['address_id'],
            'service_technician_id'=>$param['service_technician_id'],
            'service_goodid'=>$param['service_goodid'],
            'distance'=>0,
            'service_duration'=>$param['service_duration'],
            'appointment_date'=>$param['appointment_date'],
            'appointment_time'=>$param['appointment_time'],
            'time_period'=>$param['time_period'],
            'uid'=>$this->uid,
            'order_no'=>$order_no,
            'create_time'=>time(),
            'payable_money'=>$total_price,//应付金额
            'total_price'=>$total_price,//总价
            'calculate_taxi_fare'=>0,//车费
            "merchant_id"=>$param["merchant_id"]//商户id
        ];
        Db::startTrans();
        try {
            Db::name('order')->insert($data); 
            $orderId = Db::name('order')->getLastInsID();
          
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error('下单失败，请稍后重试');
        }
        Db::commit();
        $this->success('下单成功，请支付', ['order_no' => $order_no, 'orderId'=>$orderId]);
    }

    // 计算出租车费用的函数
    public function calculate_taxi_fare($distance,$starting_price,$additional_costs,$additional_fees) {
        // 基本费用和每增加1公里的额外费用
        $base_fare = $starting_price;
        $additional_fare_per_km = bcadd($additional_costs,$additional_fees,2);
        // 初始费用
        $fare = $base_fare;
        // 计算额外费用
        $additional_fare = ($distance - 3) * $additional_fare_per_km;
        // 总费用
        $fare += $additional_fare;
        return $fare;
    }

    
    /**
     * 订单支付
     */
    public function order_payment()
    {
        $param = $this->request->param();
        if (empty($param['order_no'])) {
            $this->error('未找到指定订单');
        }
        $orderData = ModelOrder::where('order_no', $param['order_no'])->where('status', 1)->where('uid', $this->uid)->find();
        if (empty($orderData)) {
            $this->error('未找到指定订单');
        } 
        $orderData = $orderData->toArray();
        //生成新的支付订单号
        $random_data = $orderData['id'].rand(1,99999).substr(time(),1,2);
        $new_order_no = $param['order_no'].$random_data;
    
        $openid = User::where('id', $orderData['uid'])->value("wx_openid");
        $http = is_https() ? 'https' : 'http';
        $notify = $http . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/api/notify/wechat_notify';
        $wechat = new Pay($this->wechat_config);

        $options = [
            'body' => '订单支付',
            'out_trade_no' => $new_order_no,
            'attach'=>1,//1、正常单第一次支付
            'total_fee' => bcmul($orderData['payable_money'], 100),
            'openid' => $openid,
            'trade_type' => 'JSAPI',
            'notify_url' => $notify,
            'spbill_create_ip' => '127.0.0.1',
        ];
        $result = $wechat->createOrder($options);
        if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == 'OK') {
            $ret = $wechat->createParamsForJsApi($result['prepay_id']);
            $order_record = Db::name('order_record')->where('oid',$orderData['id'])->find();
            if(empty($order_record)){
                Db::name('order_record')->insert(['oid'=>$orderData['id'],'order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }else{
                Db::name('order_record')->where('oid',$orderData['id'])->update(['order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }
            $this->success('ok', $ret);
        } else {
            $this->error("支付失败");
        }
       
    }

    /**
     * 退款  status = 2的时候可以退款
     */
    public function cancle_order(ModelOrder $order)
    {
        $param = $this->request->param();
        if (empty($param['order_no'])) {
            $this->error('未找到指定订单');
        }
        $ret = $order->where('order_no', $param['order_no'])->where('status', 2)->where('uid', $this->uid)->find();
        if (empty($ret)) {
            $this->error('当前订单不能退款');
        }
        if ($ret['payable_money'] == 0) {
            $order->where('id', $ret['id'])->update(['status' => 3]);
            Db::name('art_performance')->where('id',$ret['apid'])->inc('num',$ret['num'])->update();
            $this->success('退款成功');
        } else {//需要退款
            $result = $this->wxchat_back($ret['transaction_id'], $ret['order_no'], $ret['payable_money'] * 100);
            if($result['code'] == 1){
                $order->where('id', $ret['id'])->update(['status' => 3]);
                Db::name('art_performance')->where('id',$ret['apid'])->inc('num',$ret['num'])->update();
                $this->success('退款成功', '');
            } else {
                $order->where('id', $ret['id'])->update(['fail_msg' => $result['msg']]);
                $this->error('退款失败');
            }
        }
    }

    //取消订单
    public function cancellation_of_order(ModelOrder $order){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('未找到指定订单');
        }
        $ret = $order->where('id', $param['oid'])->where('status', 1)->where('uid', $this->uid)->find();
        if (empty($ret)) {
            $this->error('当前订单不能取消');
        }
        $order->where('id', $param['oid'])->update(["status"=>8]);
     //   $order->destroy($param['oid']);
        $this->success('取消成功');
    }


    public function wxchat_back($transaction_id, $out_refund_no, $money)
    {
        try {
            $wechat = \WeChat\Pay::instance($this->wechat_config);
             $options = [
                'transaction_id' => $transaction_id,
                'out_refund_no'  => $out_refund_no,
                'total_fee'      => $money,
                'refund_fee'     => $money,
            ];
            $result = $wechat->createRefund($options);
            if ($result['return_code'] == 'SUCCESS' && $result['result_code'] == 'SUCCESS') {
                return ['code' =>1, 'data' => $result];
            } else{
                return ['code'=>0, 'msg'=>$result['err_code_des']];
            }
        } catch (\Throwable $th) {
            return ['code'=>0, 'msg'=>$th->getMessage()];
        }
    }


    /**
     * 订单列表
     */
    public function order_list(ModelOrder $order)
    {
        $param = $this->request->param();
        $status = empty($param['type'])?0:$param['type'];
        $where = [['uid', '=', $this->uid]];
        if ($status == 1) {//待付款
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 1]
            ];
        }
        if ($status == 2) {//待服务
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 2]
            ];
        }
        if ($status == 3) {//待确认
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 3]
            ];
        }
        if ($status == 4) {//待评价
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 4]
            ];
        }
        if ($status == 7) {//已完成
            $where = [
                ['uid', '=', $this->uid],
                ['status', '=', 7]
            ];
        }
      
        if ($status == 0) {//全部
            $where = [
                ['uid', '=', $this->uid],
                ['status', 'in', '1,2,3,4,7,8']
            ];
        }
        $list = $order->where($where)->order('create_time', 'desc')
            ->paginate(10)->each(function($item){
                $service_goods = Db::name("service_goods")->where("id",$item["service_goodid"])->find();
                $service_technician = Db::name("service_technician")->where("id",$item["service_technician_id"])->find();
                $address = Db::name("address")->where("id",$item["address_id"])->find();

                
                
                $item["address"] = $address;
                $item["service_technician"] = $service_technician;
                $item["service_goods"] = $service_goods;
                return $item;
            });
        $this->success('查询成功', $list);
       
    }


    /**
     * 订单详情
     */
    public function order_detail()
    {
        $param = $this->request->param();
        if (empty($param['order_id'])) {
            $this->error('未找到指定订单');
        }
        $ret = Db::name("order")->where('id', $param['order_id'])->where('uid', $this->uid)->find();
        if (empty($ret)) {
            $this->error('订单不存在');
        }
        $order_item = Db::name("order_item")->where("oid",$param["order_id"])->find();
        $service_goods = Db::name('service_goods')->where('id',$order_item['service_goods_id'])->field("id,title,zhu_img,price,duration")->find();
        $ret["service_technician"] = Db::name("service_technician")->where("id",$order_item["service_technician_id"])->field("id,service_name,service_img,score")->find();
     
       
        $adderss = Db::name("address")->where("id",$ret["address_id"])->find();
        $ret['adderss'] = $adderss;
        
        $ret['service_goods'] = $service_goods;
        $this->success('查询成功', $ret);
    }

    //订单评价
    public function order_evaluate(){
        $param = $this->request->param();
        if (empty($param['order_id'])) {
            $this->error('未找到指定订单');
        }
        if (empty($param['star_rating'])) {
            $this->error('星级不能为空');
        }
        if (empty($param['content'])) {
            $this->error('评价内容不能为空');
        }
        $order = Db::name("order")->where("id",$param['order_id'])->find();
        if(empty($order)){
            $this->error('订单不存在');
        }
 
        $data = [
            "uid"=>$this->uid,
            "oid"=>$param['order_id'],
            "service_technician_id"=>$order["service_technician_id"],
            "star_rating"=>$param['star_rating'],
            "content"=>$param['content'],
            "create_time"=>time(),
        ];
        Db::name("order_evaluate")->insert($data);
        Db::name("order")->where("id",$param["order_id"])->update(["status"=>7]);

        //更新技师评分
        $yixing = Db::name("order_evaluate")->where("service_technician_id",$order["service_technician_id"])->where("star_rating",1)->count();
        $erxing = Db::name("order_evaluate")->where("service_technician_id",$order["service_technician_id"])->where("star_rating",2)->count();
        $sanxing = Db::name("order_evaluate")->where("service_technician_id",$order["service_technician_id"])->where("star_rating",3)->count();
        $sixing = Db::name("order_evaluate")->where("service_technician_id",$order["service_technician_id"])->where("star_rating",4)->count();
        $wuxing = Db::name("order_evaluate")->where("service_technician_id",$order["service_technician_id"])->where("star_rating",5)->count();

        //得分 = 星级 * 数量
        $defen = bcmul($yixing,1) + bcmul($erxing,2) + bcmul($sanxing,3) + bcmul($sixing,4) + bcmul($wuxing,5);

        $num = $yixing + $erxing + $sanxing + $sixing + $wuxing;

        $pingfen = bcdiv($defen,$num,2);
        
        Db::name("service_technician")->where("id",$order["service_technician_id"])->update(["score"=>$pingfen]);
 
        $this->success('评论成功');
    }


    //打赏
    public function reward_pay(){
        $param = $this->request->param();
        if (empty($param['reward_money'])) {
            $this->error('打赏金额不能为空');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('达人id不能为空');
        }
        if($param['reward_money'] < 0.5){
            $this->error('打赏金额不能小于5毛');
        }

        $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $param['service_technician_id'];
        $data = [
            'service_technician_id'=>$param['service_technician_id'],
            'reward_money'=>$param['reward_money'],
            'uid'=>$this->uid,
            'sub_order_no'=>$order_no,
            'create_time'=>time(),
        ];
        Db::name('order_price_difference')->insert($data); 
        $this->dashang_supplementary_pay($order_no);
    }
  
    //打赏支付
    public function dashang_supplementary_pay($order_no){
        $orderData = DB::name("order_price_difference")->where('sub_order_no', $order_no)->where('status', 0)->where('uid', $this->uid)->find();
        if (empty($orderData)) {
            $this->error('未找到指定订单');
        }
       
        //生成新的支付订单号
        $random_data = $orderData['id'].rand(1,99999).substr(time(),1,2);
        $new_order_no = $order_no.$random_data;
        
        $openid = User::where('id', $orderData['uid'])->value("wx_openid");
        
        $http = is_https() ? 'https' : 'http';
        $notify = $http . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/api/notify/reward_notify';
        $wechat = new Pay($this->wechat_config);
        $options = [
            'body' => '订单支付',
            'out_trade_no' => $new_order_no,
            'attach'=>1,//1、正常单第一次支付
            'total_fee' => bcmul($orderData['reward_money'], 100),
            'openid' => $openid,
            'trade_type' => 'JSAPI',
            'notify_url' => $notify,
            'spbill_create_ip' => '127.0.0.1',
        ];
        $result = $wechat->createOrder($options);
        if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == 'OK') {
            $ret = $wechat->createParamsForJsApi($result['prepay_id']);
            $order_record = Db::name('order_record')->where('oid',$orderData['id'])->where('type',1)->find();
            if(empty($order_record)){
                Db::name('order_record')->insert(['oid'=>$orderData['id'],'type'=>1,'order_no'=>$order_no,'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }else{
                Db::name('order_record')->where('oid',$orderData['id'])->where('type',1)->update(['order_no'=>$order_no,'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }
            $this->success('ok', $ret);
        } else {
            $this->error("支付失败");
        }
    }

    //打赏记录
    public function reward_records(){
        $param = $this->request->param();
        //type 1用户  2陪玩
        if (empty($param['type'])) {
            $this->error("类型不能为空");
        }
         
        if($param["type"] == 1){
            $list = Db::name("order_price_difference")->where("uid",$this->uid)->where("status",1)
            ->paginate(10)->each(function($item){
                $service_technician = Db::name("service_technician")->where("id",$item["service_technician_id"])->field("id,service_name,service_img")->find();
                $user = Db::name("user")->where("id",$this->uid)->field("id,nickname")->find();
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                if(!empty($item["pay_time"])){
                    $item["pay_time"] = date("Y-m-d H:i:s",$item["pay_time"]);
                }
                $item["service_technician"] = $service_technician;
                $item["user"] = $user;
                return $item;
            });

        }elseif($param["type"] == 2){
            if (empty($param['sid'])) {
                $this->error("达人id不能为空");
            }
            $list = Db::name("order_price_difference")->where("service_technician_id",$param['sid'])->where("status",1)
            ->paginate(10)->each(function($item){
                $service_technician = Db::name("service_technician")->where("id",$item["service_technician_id"])->field("id,service_name,service_img")->find();
                $user = Db::name("user")->where("id",$this->uid)->field("id,nickname")->find();
                $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                if(!empty($item["pay_time"])){
                    $item["pay_time"] = date("Y-m-d H:i:s",$item["pay_time"]);
                }
                $item["service_technician"] = $service_technician;
                $item["user"] = $user;
                return $item;
            });

        }else{
            $this->error("类型不存在");
        }


       
        $this->success('获取成功', $list);
    }
 
    //修改提现密码
    public function set_withdrawal_password()
    {
        $param = $this->request->param();
        if (empty($param['old_password'])) {
            $this->error("原密码不能为空");
        }
        if (empty($param['password'])) {
            $this->error("新密码不能为空");
        }
        if (empty($param['new_password'])) {
            $this->error("确认新密码不能为空");
        }
        $member = Db::name('user')->where('id', $this->uid)->find();
        if ($member['withdrawal_password'] != md5(md5($param['old_password']))) {
            $this->error("原密码错误");
        }
        if ($param['password'] != $param['new_password']) {
            $this->error("两次密码不一致");
        }
        Db::name('user')->where('id', $this->uid)->update(['withdrawal_password' => md5(md5($param['password']))]);
        $this->success('设置成功');
    }

    //设置提现密码
    public function edit_withdrawal_password()
    {
        $param = $this->request->param();
        if (empty($param['password'])) {
            $this->error("密码不能为空");
        }
        if (empty($param['new_password'])) {
            $this->error("确认密码不能为空");
        }
        if ($param['password'] != $param['new_password']) {
            $this->error("两次密码不一致");
        }
        Db::name('user')->where('id', $this->uid)->update(['withdrawal_password' => md5(md5($param['password']))]);
        $this->success('设置成功');
    }

    //检查提现密码是否已设置
    public function is_set_pwd()
    {
        $flag = Db::name('user')->where('id', $this->uid)->find()['withdrawal_password'];
        if (empty($flag)) {
            $this->error("未设置");
        } else {
            $this->success('已设置');
        }
        
    }

    //验证密码是否正确
    public function verify_password(){
        $param = $this->request->param();
        if (empty($param['password'])) {
            $this->error("参数错误");
        }
        $user = Db::name('user')->where('id', $this->uid)->find();
        if(empty($user["withdrawal_password"])){
            $this->error("请先设置提现密码");
        }
        if ($user['withdrawal_password'] != md5(md5($param['password']))) {
            $this->error("密码错误");
        }
        $this->success('密码正确可以提现');
    }

    //佣金提现
    public function balance_withdrawal()
    {
        $param = $this->request->param();
        //type 1分销商   2陪玩
        if (empty($param['type'])) {
            $this->error("参数错误");
        }
        if (empty($param['money'])) {
            $this->error("提现金额不能为空");
        }
        if (empty($param['phone'])) {
            $this->error("提现手机号不能为空");
        }
        if (empty($param['real_name'])) {
            $this->error("真实姓名不能为空");
        }
        $user = Db::name("user")->where('id', $this->uid)->find();
        if(empty($user['service_technician_id'])){
            $this->error("用户未绑定不可提现");
        }
        //判断佣金是否足够 
        if($param["type"] == 1){
            $commission = $user["commission"];
        }elseif($param["type"] == 2){
            $commission = Db::name('service_technician')->where('id', $user['service_technician_id'])->find()['ke_blanace'];
        }else{
            $this->error("类型错误");
        }
        if ($param['money'] > $commission) {
            $this->error("佣金不足");
        }
        $data_w = [
            'uid' => $this->uid,
            'type' => $param['type'],
            'money' => $param['money'],
            'desc' => $param['desc'],
            'phone' => $param['phone'],
            'service_technician_id' => $user['service_technician_id'],
            'real_name' => $param['real_name'],
            'create_time' => time(),
        ];
        Db::name('withdrawal')->insert($data_w);
        //减去佣金
        if($param["type"] == 1){
            Db::name('user')->where('id', $this->uid)->dec('commission', $param['money'])->update();
        }elseif($param["type"] == 2){
            Db::name('service_technician')->where('id', $user['service_technician_id'])->dec('ke_blanace', $param['money'])->update();
        }else{
            $this->error("类型错误");
        }
        $this->success('提现申请提交成功');

    }

    // else { //银行卡提现
    //     if (empty($data['bank_code'])) {
    //         return returnData(0, '提现银行不能为空', '');
    //     }
    //     //检查用户是否绑定银行卡
    //     $flag = Db::name('my_bank_card')->where('uid', $this->uid)->where('bank_code', $data['bank_code'])->find();
    //     if (empty($flag)) {
    //         return returnData(0, '此银行卡未绑定', '');
    //     } else {
    //         $data_y = [
    //             'uid' => $this->uid,
    //             'type' => $data['type'],
    //             'money' => $data['money'],
    //             'desc' => $data['desc'],
    //             'account_number' => $flag['bank_card_number'],
    //             'real_name' => $flag['real_name'],
    //             'phone' => $flag['phone'],
    //             'ctime' => time(),
    //         ];
    //         Db::name('withdrawal')->insert($data_y);
    //         Db::name('member')->where('id', $this->uid)->dec('balance', $data['money'])->update();
    //     }
    // }


    















  

 
    // $where = ["is_sso"=>1];
    // $whereOr = [
    //     ['os.is_cancel', '=', 1],
    //     ['o.status', 'in', "5"],
    // ];
    // $order_scanning_code = Db::name("order_scanning_code")
    // ->alias("os")
    // ->join("order o","o.id = os.oid")
    // ->where("os.service_user_id",$param["sid"])
    // ->where($where)
    // ->where(function($query) use ($whereOr){$query->whereOr($whereOr);})






 
 

    //达人登录
    public function technician_login(){
        $param = $this->request->param();
        if (empty($param['phone'])) {
            $this->error('账号不能为空');
        }
        if (empty($param['password'])) {
            $this->error('密码不能为空');
        }
        $flag = Db::name("service_technician")->where("uid",$this->uid)->where("phone",$param['phone'])->find();
        if(empty($flag)){
            $this->error('账号不存在');
        }
        if(empty($flag["uid"])){
            $this->error('用户未绑定，先绑定用户');
        }
        if(md5($param['password']) != $flag["password"]){
            $this->error('密码不正确');
        }
        $this->success('登录成功',$flag);
    }

  
    //达人服务订单
    public function in_service_order(){
        $param = $this->request->param();
        if (empty($param['sid'])) {
            $this->error('达人id不能为空');
        }
        //0全部 1待接单  2待服务  3服务中  4已完成
    
        if($param['type'] == 0){
            $where = [
                ['status', 'in', "2,3,4,7"],
            ];
        }elseif($param['type'] == 1){
            $where = [
                ['status', '=', 2],
                ['is_taking_orders', '=', 0],
            ];
        }elseif($param['type'] == 2){
            $where = [
                ['status', '=', 2],
                ['is_taking_orders', '=', 1],
            ];
        }elseif($param['type'] == 3){
            $where = [
                ['is_startaccepting_orders', '=', 1],
                ['status', '=', 3],
            ];
        }elseif($param['type'] == 4){
            $where = [
                ['is_startaccepting_orders', '=', 2],
                ['status', 'in', '4,7'],
            ];
        }else{
            $this->error('类型不存在');
        }
        $order_scanning_code = Db::name("order")
                            ->where("service_technician_id",$param["sid"])
                            ->where($where)
                            ->order("create_time desc")
                            ->paginate(10)->each(function($item){
                                $service_technician = Db::name('service_technician')->where('id',$item['service_technician_id'])->find();
                                if(!empty($service_technician)){
                                    $item['service_technician'] = $service_technician;
                                }else{
                                    $item['service_technician'] = "";
                                }
                                $service_goods = Db::name('service_goods')->where('id',$item['service_goodid'])->find();
                                if(!empty($service_goods)){
                                    $item['service_goods'] = $service_goods;
                                }else{
                                    $item['service_goods'] = "";
                                }
                                $adderss = Db::name("address")->where("id",$item["address_id"])->find();
                                if(!empty($adderss)){
                                    $item['adderss'] = $adderss;
                                }else{
                                    $item['adderss'] = "";
                                }
                                $user = Db::name("user")->where("id",$item["uid"])->field("id,nickname,phone")->find();
                                if(!empty($user)){
                                    $item['user'] = $user;
                                }else{
                                    $item['user'] = "";
                                }
                                if(!empty($item["create_time"])){
                                    $item["create_time"] = date("Y-m-d H:i:s",$item["create_time"]);
                                }else{
                                    $item['create_time'] = "";
                                }
                                if(!empty($item["pay_time"])){
                                    $item["pay_time"] = date("Y-m-d H:i:s",$item["pay_time"]);
                                }else{
                                    $item['pay_time'] = "";
                                }
                                if(!empty($item["order_acceptance_time"])){
                                    $item["order_acceptance_time"] = date("Y-m-d H:i:s",$item["order_acceptance_time"]);
                                }else{
                                    $item['order_acceptance_time'] = "";
                                }
                                if(!empty($item["start_service_time"])){
                                    $item["start_service_time"] = date("Y-m-d H:i:s",$item["start_service_time"]);
                                }else{
                                    $item['start_service_time'] = "";
                                }
                                if(!empty($item["completion_time"])){
                                    $item["completion_time"] = date("Y-m-d H:i:s",$item["completion_time"]);
                                }else{
                                    $item['completion_time'] = "";
                                } 
                                return $item;
                            });
        if($param['type'] == 4){
            $map = [
                ['is_startaccepting_orders', '=', 2],
                ['status', 'in', '4,7'],
            ];                  
            $yeji = Db::name("order")->where("service_technician_id",$param["sid"])->where($map)->sum("paidin_money");
        }else{
            $yeji = 0;
        }

        //0全部 1待接单  2待服务  3服务中  4已完成
        //订单数
        $order_num = [];
        $where_0 = [['status', 'in', "2,3,4,7"],];
        $order_num["status_0order_num"] = Db::name("order")->where("service_technician_id",$param["sid"])->where($where_0)->count();

        $where_1 = [['status', '=', 2],['is_taking_orders', '=', 0]];
        $order_num["status_1order_num"] = Db::name("order")->where("service_technician_id",$param["sid"])->where($where_1)->count();

        $where_2 = [['status', '=', 2],['is_taking_orders', '=', 1]];
        $order_num["status_2order_num"] = Db::name("order")->where("service_technician_id",$param["sid"])->where($where_2)->count();

        $where_3 = [['is_startaccepting_orders', '=', 1],['status', '=', 3] ];
        $order_num["status_3order_num"] = Db::name("order")->where("service_technician_id",$param["sid"])->where($where_3)->count();

        $where_4 = [['is_startaccepting_orders', '=', 2],['status', 'in', '4,7']];;
        $order_num["status_4order_num"] = Db::name("order")->where("service_technician_id",$param["sid"])->where($where_4)->count();
        
         

        $list = [
            "order_scanning_code"=>$order_scanning_code,
            "yeji"=>$yeji,
            "order_num"=>$order_num
        ];

        $this->success('获取成功',$list);               
    }

   
    //申请退款
    public function apply_for_refund(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        $order = Db::name("order")->where("id",$param["oid"])->where("status",2)->find();
        if(empty($order)){
            $this->error('订单不存在');
        }
        Db::name("order")->where("id",$param["oid"])->update(["is_order_refund"=>1,"update_time"=>time()]);
        $this->success("提交成功，请等待管理员审核");
    }


    //达人点击接单
    public function clicktoaccept_theorder(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('达人id不能为空');
        }
        $flag = Db::name("order")->where("status",2)->where("id",$param["oid"])->where("service_technician_id",$param["service_technician_id"])->where("is_taking_orders",1)->find();
        if(!empty($flag)){
            $this->error('此订单已被接');
        }
        Db::name("order")->where("status",2)->where("id",$param["oid"])->where("service_technician_id",$param["service_technician_id"])->update(["is_taking_orders"=>1,"status"=>2,"order_acceptance_time"=>time()]);
        $this->success("接单成功");
    }
 

    //达人点击接开始服务
    public function clickstart_service(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('达人id不能为空');
        }
        $flag = Db::name("order")->where("status",3)->where("id",$param["oid"])->where("service_technician_id",$param["service_technician_id"])->where("is_startaccepting_orders",1)->find();
     
        if(!empty($flag)){
            $this->error('此订单已开始服务');
        }
        Db::name("order")->where("status",2)->where("id",$param["oid"])->where("service_technician_id",$param["service_technician_id"])->update(["status"=>3,"start_service_time"=>time(),"is_startaccepting_orders"=>1]);
        //修改达人状态为忙碌 status_type 0离线，1在线，2忙碌
        Db::name("service_technician")->where("id",$param["service_technician_id"])->update(["status_type"=>2]);
        $this->success("操作成功");
    }
 

    //达人点击完成服务
    public function technician_completes_service(){
        $param = $this->request->param();
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        if (empty($param['service_technician_id'])) {
            $this->error('达人id不能为空');
        }
        $flag = Db::name("order")->where("id",$param["oid"])->where("status",4)->where("is_startaccepting_orders",2)->find();
        if(!empty($flag)){
            $this->error('此订单已确认');
        }
        Db::name("order")->where("id",$param["oid"])->where("status",3)->update(["status"=>4,"completion_time"=>time(),"is_startaccepting_orders"=>2]);
        //增加订单销量
        Db::name("service_technician")->where("id",$param["service_technician_id"])->inc("sales_volume",1)->update();
        //修改达人状态为在线 status_type 0离线，1在线，2忙碌
        Db::name("service_technician")->where("id",$param["service_technician_id"])->update(["status_type"=>1]);

        //状态修改成功，给上级和商家返佣
        //查询订单更新佣金
        $order = Db::name("order")->where("id",$param["oid"])->find();
        if(!empty($order)){
           //修改陪玩业绩
           Db::name("service_technician")->where("id",$order["service_technician_id"])->inc("balance",$order["payable_money"])->update();
           //陪玩提成比例
           $playwith_ratio = sysconfig("pw","playwith_ratio");
           $playwithratio = bcdiv($playwith_ratio,100,2);
           $ke_blanace = bcmul($order["payable_money"],$playwithratio);
           //给陪玩返可提现佣金
           Db::name("service_technician")->where("id",$order["service_technician_id"])->inc("ke_blanace",$ke_blanace)->update();
           //陪玩加入佣金记录
           $data_p = [
                "uid"=>$order["uid"],
                "type"=>3,
                "service_technician_id"=>$order["service_technician_id"],
                "proportion_ratio"=>$playwithratio,
                "money"=>$ke_blanace,
                "oid"=>$order["id"],
                "create_time"=>time(),
           ];
           Db::name("commission_record")->insert($data_p);
 
           //商户，分销提成比例
           $merchant_ratio = sysconfig("sh","merchant_ratio");
           $merchantratio = bcdiv($merchant_ratio,100,2);
           $commission = bcmul($order["payable_money"],$merchantratio);
           //商户返佣
           if($order["merchant_id"] > 0){
                Db::name("merchant")->where("id",$order["merchant_id"])->inc("commission",$commission)->update();
                //加入佣金记录
                $data_c = [
                    "uid"=>$order["uid"],
                    "type"=>2,
                    "merchant_id"=>$order["merchant_id"],
                    "proportion_ratio"=>$merchantratio,
                    "money"=>$commission,
                    "oid"=>$order["id"],
                    "create_time"=>time(),
                ];
                Db::name("commission_record")->insert($data_c);
           }

           //分销商返佣
           $user = Db::name("user")->where("id",$order["uid"])->field("superior_fid")->find();
           if($user["superior_fid"] > 0){
                Db::name("user")->where("id",$order["superior_fid"])->inc("commission",$commission)->update();
                //加入佣金记录
                $data_u = [
                    "uid"=>$order["uid"],
                    "type"=>1,
                    "superior_fid"=>$user["superior_fid"],
                    "proportion_ratio"=>$merchantratio,
                    "money"=>$commission,
                    "oid"=>$order["id"],
                    "create_time"=>time(),
                ];
                Db::name("commission_record")->insert($data_u);
           }
          
        }
 
        $this->success("确认成功");
    }

 

    //测试定时自动完成服务
    public function rtse(){
        $order = new User();
        $asda = $order->complete_theservice();
        $this->success("确认成功",$asda);
    }

      //技师端平台取消订单
    public function teach_cancel_order(){
        $param = $this->request->param();
        if (empty($param['sid'])) {
            $this->error('技师id不能为空');
        }
     
        $where = [
            ['os.is_cancel', '=', 1]
        ];
        $order_scanning_code = Db::name("order_scanning_code")
                            ->alias("os")
                            ->join("order o","o.id = os.oid")
                            ->where("os.service_user_id",$param["sid"])
                            //->where("os.is_confirm",$osis_confirm)
                            ->where($where)
                            // ->where("os.status",$osstatus)
                            // ->where("o.status",$ostatus)
                            ->field("os.id as osid,os.status as osstatus,os.service_user_id,o.id as oid,o.order_no,o.service_time,o.status as ostatus,o.service_gid,o.spec_id,o.address_id,o.create_time,o.type,os.is_cancel")
                            ->paginate(10)->each(function($item){
                                $service_duration = Db::name('service_duration')->where('id',$item['spec_id'])->find();
                                $service_goods = Db::name('service_goods')->where('id',$item['service_gid'])->field("id,title,zhu_img")->find();
                                if(!empty($service_duration)){
                                    $sku_attribute_list = json_decode($service_duration["specs_list"],true);
                                    $item['spec_data'] = $sku_attribute_list;
                                    $service_goods["price"] = $service_duration["price"];
                                }else{
                                    $order_item = Db::name("order_item")->where("oid",$item["oid"])->find();
                                    $sku_attribute_list = json_decode($order_item["specs_list"],true);
                                    $item['spec_data'] = $sku_attribute_list;
                                    $service_goods["price"] = $order_item["price"];
                                }
                                $item['service_goods'] = $service_goods;
                                $adderss = Db::name("address")->where("id",$item["address_id"])->find();
                                if(!empty($adderss)){
                                    $item['adderss'] = $adderss;
                                }else{
                                    $item['adderss'] = "";
                                }
                                //判断是否有差价订单
                                $flag = Db::name("order_price_difference")->where("oid",$item["oid"])->find();
                                if(empty($flag)){
                                    $item['is_check'] = false;
                                }else{
                                    $item['is_check'] = true;
                                }

                                //判断是否已确认
                                $flag_qew = Db::name("order_scanning_code")->where("oid",$item["oid"])->where("is_confirm",1)->find();
                                if(empty($flag_qew)){
                                    $item['is_confirm'] = false;
                                }else{
                                    $item['is_confirm'] = true;
                                }
                                return $item;
                            });
        $this->success('获取成功',$order_scanning_code);      
    }


     //技师端补交费用创建订单
     public function supplementary_fees(){
        $param = $this->request->param();
        if (empty($param['service_user_id'])) {
            $this->error('技师id不能为空');
        }
        if (empty($param['oid'])) {
            $this->error('订单id不能为空');
        }
        if (empty($param['money'])) {
            $this->error('金额不能为空');
        }
        $order_no = date('Ymd') . substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8) . $param['service_user_id'];
        $data = [
            'service_user_id'=>$param['service_user_id'],
            'money'=>$param['money'],
            'oid'=>$param['oid'],
            'sub_order_no'=>$order_no,
            'create_time'=>time(),
        ];
        Db::startTrans();
        try {
            Db::name('order_price_difference')->insert($data); 
            $orderId = Db::name('order_price_difference')->getLastInsID();
        } catch (\Throwable $th) {
            Db::rollback();
            $this->error('补交费用下单失败，请稍后重试');
        }
        Db::commit();
        $this->success('补交费用下单成功，请支付', ['order_no' => $order_no, 'orderId'=>$orderId]);
    }

    //用户端支付补交费用
    public function user_supplementary_pay(){
        $param = $this->request->param();
        if (empty($param['order_no'])) {
            $this->error('未找到指定订单');
        }
        //更新用户id到差价订单表
        Db::name("order_price_difference")->where('sub_order_no', $param['order_no'])->where('status', 0)->update(["uid"=>$this->uid]);
        
        $orderData = DB::name("order_price_difference")->where('sub_order_no', $param['order_no'])->where('status', 0)->where('uid', $this->uid)->find();
        if (empty($orderData)) {
            $this->error('未找到指定订单');
        }
       
        //生成新的支付订单号
        $random_data = $orderData['id'].rand(1,99999).substr(time(),1,2);
        $new_order_no = $param['order_no'].$random_data;
        
        $openid = User::where('id', $orderData['uid'])->value("wx_openid");
       //$openid = "oahPO4mRtWNhE1pRejVcurqOTLMQ";
        $http = is_https() ? 'https' : 'http';
        $notify = $http . '://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . '/api/notify/makeup_notify';
        $wechat = new Pay($this->wechat_config);
        $options = [
            'body' => '订单支付',
            'out_trade_no' => $new_order_no,
            'attach'=>1,//1、正常单第一次支付
            'total_fee' => bcmul($orderData['money'], 100),
            'openid' => $openid,
            'trade_type' => 'JSAPI',
            'notify_url' => $notify,
            'spbill_create_ip' => '127.0.0.1',
        ];
        $result = $wechat->createOrder($options);
        if ($result['return_code'] == "SUCCESS" && $result['return_msg'] == 'OK') {
            $ret = $wechat->createParamsForJsApi($result['prepay_id']);
            $order_record = Db::name('order_record')->where('oid',$orderData['id'])->where('type',1)->find();
            if(empty($order_record)){
                Db::name('order_record')->insert(['oid'=>$orderData['id'],'type'=>1,'order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }else{
                Db::name('order_record')->where('oid',$orderData['id'])->where('type',1)->update(['order_no'=>$param['order_no'],'random_data'=>$random_data,'new_order_no'=>$new_order_no]);
            }
            $this->success('ok', $ret);
        } else {
            $this->error("支付失败");
        }
    }

     
    //我的优惠券
    public function my_coupon_list(){
        $param = $this->request->post();
        if(empty($param["type"])){
            $this->error("类型不能为空");
        }
       
        Db::name("coupon_user")->where("uid",$this->uid)
            ->where("status",$param["type"])
            ->paginate(10)->each(function($item){
                $time = date("Y-m-d H:i:s",time());
                $coupon = Db::name("coupon")->where("id",$item["coupon_id"])->field("endtime,title,full_amount,less_amount")->find();
                if($coupon["endtime"] < $time){
                    Db::name("coupon_user")->where("id",$item["id"])->update(["status"=>3]);
                }
            });
        $list = Db::name("coupon_user")->where("uid",$this->uid)
            ->where("status",$param["type"])
            ->paginate(10)->each(function($item){
                $coupon = Db::name("coupon")->where("id",$item["coupon_id"])->field("endtime,title,full_amount,less_amount")->find();
                $item["coupon_endtime"] = $coupon["endtime"];
                $item["title"] = $coupon["title"];
                $item["full_amount"] = $coupon["full_amount"];
                $item["less_amount"] = $coupon["less_amount"];
                return $item;
            });
      
        $this->success('获取成功',$list);
    }
 

    //取消退款
    public function order_cancel_refund(){
        $param = $this->request->post();
        if(empty($param["oid"])){
            $this->error("订单id不能为空");
        }
        $order = Db::name("order")->where("id",$param["oid"])->where("status",6)->find();
        if(empty($order)){
            $this->error("此订单不能取消退款");
        }
        Db::name("order")->where("id",$param["oid"])->update(["status"=>2,"is_order_refund"=>0]);
        $this->success("取消成功");
    }
 
    
  

  
   

}
